//
//  EventKitController.m
//  TestCalendar
//
//  Created by mal on 14-1-9.
//  Copyright (c) 2014年 mal. All rights reserved.
//

#import "EventKitController.h"

NSString *const RemindersModelChangedNotification = @"RemindersModelChangedNotification";
NSString *const RemindersAccessGranted = @"RemindersAccessGranted";

@implementation EventKitController
@synthesize eventStore;
@synthesize eventAccess;
@synthesize reminderAccess;

@synthesize reminders;

- (id)init
{
    if(self = [super init])
    {
        eventStore = [[EKEventStore alloc] init];
//        [eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error){
//            if(granted)
//            {
//                eventAccess = YES;
//            }
//            else
//            {
//                NSLog(@"event access not granted:%@", error);
//            }
//        }];
        [eventStore requestAccessToEntityType:EKEntityTypeReminder completion:^(BOOL granted, NSError *error){
            if(granted)
            {
                reminderAccess = YES;
                [[NSNotificationCenter defaultCenter] postNotificationName:RemindersAccessGranted object:self];
            }
            else
            {
                NSLog(@"reminder access not granted:%@", error);
            }
        }];
    }
    return self;
}

- (EKCalendar*)calendarForReminders
{
    for(EKCalendar *calendar in [self.eventStore calendarsForEntityType:EKEntityTypeReminder])
    {
        if([calendar.title isEqualToString:kRemindersCalendarTitle])
        {
            return calendar;
        }
    }
    EKCalendar *remindersCalendar = [EKCalendar calendarForEntityType:EKEntityTypeReminder eventStore:self.eventStore];
    remindersCalendar.title = kRemindersCalendarTitle;
    remindersCalendar.source = self.eventStore.defaultCalendarForNewReminders.source;
    NSError *err;
    BOOL success = [self.eventStore saveCalendar:remindersCalendar commit:YES error:&err];
    if(!success)
    {
        NSLog(@"%@", err.description);
        return nil;
    }
    return remindersCalendar;
}

- (BOOL)addReminderWithTitle:(NSString *)title dueTime:(NSDate *)dueDate mode:(int)recurrenceMode
{
    if(!reminderAccess)
    {
        return NO;
    }
    EKReminder *reminder = [EKReminder reminderWithEventStore:self.eventStore];
    reminder.title = title;
    reminder.calendar = [self calendarForReminders];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit;
    NSDateComponents *dueDateComponents = [calendar components:unitFlags fromDate:dueDate];
    reminder.dueDateComponents = dueDateComponents;
    EKAlarm *alarm = [EKAlarm alarmWithAbsoluteDate:dueDate];
    [reminder addAlarm:alarm];
    if(recurrenceMode==-1)
    {
    }
    else
    {
        EKRecurrenceRule *rule = [[EKRecurrenceRule alloc] initRecurrenceWithFrequency:recurrenceMode interval:1 end:nil];
        reminder.recurrenceRules = @[rule];
    }
    NSError *err;
    BOOL success = [self.eventStore saveReminder:reminder commit:YES error:&err];
    return success;
}

- (BOOL)saveRminder:(EKReminder *)reminder
{
    NSError *err;
    BOOL success = [self.eventStore saveReminder:reminder commit:YES error:&err];
    return success;
}

- (BOOL)removeReminder:(EKReminder *)reminder
{
    NSError *err;
    BOOL success = [self.eventStore removeReminder:reminder commit:YES error:&err];
    return success;
}

- (void)addEventWithName:(NSString *)eventName startTime:(NSDate *)startDate endTime:(NSDate *)endDate
{
    if(!eventAccess)
    {
        return;
    }
    EKEvent *event = [EKEvent eventWithEventStore:self.eventStore];
    event.title = eventName;
    event.startDate = startDate;
    event.endDate = endDate;
    EKAlarm *alarm = [EKAlarm alarmWithRelativeOffset:-1800];
    [event addAlarm:alarm];
    event.notes = @"this will be exciting";
    //
    EKRecurrenceRule *rule = [[EKRecurrenceRule alloc] initRecurrenceWithFrequency:EKRecurrenceFrequencyMonthly interval:1 end:nil];
    event.recurrenceRules = @[rule];
    event.calendar = self.eventStore.defaultCalendarForNewEvents;
    NSError *err;
    BOOL success = [self.eventStore saveEvent:event span:EKSpanThisEvent commit:YES error:&err];
    if(!success)
    {
        NSLog(@"there was an error");
    }
}

- (void)fetchAllReminders
{
    NSPredicate *predicate = [self.eventStore predicateForRemindersInCalendars:@[[self calendarForReminders]]];
    [self.eventStore fetchRemindersMatchingPredicate:predicate completion:^(NSArray *reminders1){
        self.reminders = [reminders1 mutableCopy];
        [[NSNotificationCenter defaultCenter] postNotificationName:RemindersModelChangedNotification object:self];
    }];
}

- (void)startBroadcastingModelChangedNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(fetchAllReminders) name:EKEventStoreChangedNotification object:self.eventStore];
}

- (void)stopBroadcastingModelChangedNotifications
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)reminder:(EKReminder *)reminder setCompletionFlagTo:(BOOL)completionFlag
{
    reminder.completed = completionFlag;
    NSError *err;
    BOOL success = [self.eventStore saveReminder:reminder commit:YES error:&err];
    if(!success)
    {
        NSLog(@"save field");
    }
}

- (void)showVC
{
}

@end
